#include "pointcloudpage.h"
#include "ui_pointcloudpage.h"
#include <QThread>

PointCloudPage::PointCloudPage(QWidget *parent) : QWidget(parent),
                                                  ui(new Ui::PointCloudPage)
{
    ui->setupUi(this);

    // 创建m_openglWidget时以ui->openGLWidget作为父窗口
    m_openglWidget = new OpenglWidget(ui->openGLWidget);

    // 设置m_openglWidget的尺寸策略
    m_openglWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 获取ui->openGLWidget的布局，如果不存在则创建一个
    QVBoxLayout *layout = qobject_cast<QVBoxLayout *>(ui->openGLWidget->layout());
    if (!layout)
    {
        layout = new QVBoxLayout(ui->openGLWidget);
        layout->setContentsMargins(0, 0, 0, 0); // 设置边距为0
    }

    // 将m_openglWidget添加到布局中
    layout->addWidget(m_openglWidget);

    connect(ui->pushButton_on, &QPushButton::clicked, this, &PointCloudPage::onStart);
    // ui->pushButton_on->setVisible(false);
}

PointCloudPage::~PointCloudPage()
{
    delete ui;
}

void PointCloudPage::onStart()
{
    std::vector<QVector3D> cloud;
    cloud = ReadVec3PointCloudASC(m_path);
    m_openglWidget->showPointCloud(cloud);
}

std::vector<QVector3D> PointCloudPage::ReadVec3PointCloudASC(QString path)
{
    std::vector<QVector3D> cloud;
    QFile file(path);
    if (!file.open(QFile::ReadOnly | QIODevice::Text))
    {
        qDebug() << "There is no asc file";
        return cloud;
    }
    QTextStream in(&file);
    QString ramData = in.readAll();
    QStringList list = ramData.split("\n");
    QStringList listline;
    cloud.resize(list.count() - 1);
    for (int i = 0; i < list.count() - 1; i++)
    {
        listline = list.at(i).split(" ");
        if (listline.size() >= 3)
        {
            cloud[i].setX((listline.at(0).toFloat()));
            cloud[i].setY((listline.at(1).toFloat()));
            cloud[i].setZ((listline.at(2).toFloat()));
        }
    }
    return cloud;
}
